﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using SystemCommon;
using PowerMonitor.BaseCtrl;
using PowerMonitor.Common;
using PowerMonitor.ModbusDev;
using PowerMonitor.Properties;

namespace PowerMonitor
{
    public partial class ShowDevValue : baseDockForm
    {
        private readonly string _strRootName = "SysDevList";
        //private readonly string _strRootText = Resources.txtMeterList;
        private int m_iChlId = -1;
        private int m_iDevId = -1;
        public ShowDevValue()
        {
            InitializeComponent();
        }
        bool m_bLoad = false;
        private void ShowDevValue_Load(object sender, EventArgs e)
        {
            RefreshChlTree();
            LoadColumnDisCfgXml();
            m_bLoad = true;
            toolTip1.ToolTipTitle = Resources.msgTitleTip;
        }
        /// <summary>
        /// 装载个性化显示设置参数
        /// </summary>
        /// <returns></returns>
        public bool LoadColumnDisCfgXml()
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(AppMain.StartPath + "\\UserConfig\\Display.xml");
                XmlNode xnparent = doc.SelectSingleNode("ColumnDispear");
                for (int i = 0; i < ctmsDispearCol.Items.Count; i++)
                {
                    XmlNode xn = xnparent.SelectSingleNode("ToolStripMenuItem" + i.ToString());
                    if (xn == null)
                    {
                        continue;
                    }
                    if (xn.InnerText.ToLower() == "false")
                    {
                        ((ToolStripMenuItem)ctmsDispearCol.Items[i]).Checked = false;
                    }
                    else
                    {
                        ((ToolStripMenuItem)ctmsDispearCol.Items[i]).Checked = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 保存列显示设置参数
        /// </summary>
        /// <returns></returns>
        public bool SaveColumnDisCfgXml()
        {
            XmlDocument doc1 = new XmlDocument();
            try
            {
                doc1.Load(AppMain.StartPath + "\\UserConfig\\Display.xml");
                XmlNode newNodeParent = doc1.CreateElement("ColumnDispear");

                for (int i = 0; i < ctmsDispearCol.Items.Count; i++)
                {
                    XmlNode xn = doc1.CreateElement("ToolStripMenuItem" + i.ToString());
                    xn.InnerText = ((ToolStripMenuItem)ctmsDispearCol.Items[i]).Checked.ToString();
                    newNodeParent.AppendChild(xn);
                }
                doc1.AppendChild(newNodeParent);
                doc1.Save(AppMain.StartPath + "\\UserConfig\\Display.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 设置列显示设置参数（对应菜单）
        /// </summary>
        /// <param name="index">菜单的</param>
        /// <returns></returns>
        public bool ModifyNode(int index)
        {
            if (!m_bLoad)
            {
                return false;
            }
            XmlDocument doc = new XmlDocument();
            try
            {
                try
                {
                    doc.Load(AppMain.StartPath + "\\UserConfig\\Display.xml");
                }
                catch 
                {
                }
                XmlNode xnparent = doc.SelectSingleNode("ColumnDispear");
                if (xnparent == null)
                {
                    xnparent = doc.CreateElement("ColumnDispear");
                }

                XmlNode xn =xnparent.SelectSingleNode("ToolStripMenuItem" + index.ToString());
                if (xn == null)
                {
                    xn = doc.CreateElement("ToolStripMenuItem" + index.ToString());
                }
                xn.InnerText = ((ToolStripMenuItem)ctmsDispearCol.Items[index]).Checked.ToString();
                xnparent.AppendChild(xn);
                doc.AppendChild(xnparent);             
                doc.Save(AppMain.StartPath + "\\UserConfig\\Display.xml");
              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            if (dt.Second == 0)    //(dt.Minute+1)%5==0&&
            {
                AppMain.BeginSaveToHistory();  // 启动存储线程
            }
            if (tvDevices.SelectedNode == null)
            {
                return;
            }
            bool isRuning = false;
            foreach (var channel in AppMain.ChlList)
            {
                isRuning = channel.GetChannelState();
                if (isRuning)
                {
                    break;
                }
            }
            btnSaveDevConfig.Enabled = !isRuning;
            btnSavePara.Enabled = !isRuning;
            RefreshValue(m_iChlId, m_iDevId);
            
        }

        public bool RefreshChlTree()
        {
            TreeNode tn = null;
            int ChlCnt = 0;
            tvDevices.Nodes.Clear(); // 清空所有
            TreeNode RootNode = new TreeNode(Resources.txtMeterList);//_strRootText
            RootNode.Name = _strRootName;
            RootNode.ImageIndex = 1;
            RootNode.SelectedImageIndex = 0;
            tvDevices.Nodes.Add(RootNode);
            for (int i = 0; i < AppMain.ChlList.Count; i++)
            {
                tn = new TreeNode();
                ChlCnt++;
                tn.Name = AppMain.ChlList[i].baseChlPara.ChannelId.ToString();// 通道名称 以及 装置名称 均使用ID(ChlId DevId)作为标识
                tn.Text = AppMain.ChlList[i].baseChlPara.ChannelName;         // 显示名称可自定义
                RefreshDevTree(ref tn, AppMain.ChlList[i]);                   // 初始化通道下的装置名称列表
                tvDevices.Nodes[0].Nodes.Add(tn);
            }
            tvDevices.ExpandAll();
            if (ChlCnt == 0)
            {
                return false;
            }
            else
            {
                if (tvDevices.TopNode != null && tvDevices.TopNode.Nodes.Count > 0 && tvDevices.TopNode.FirstNode.Nodes.Count>0)
                {
                    tvDevices.SelectedNode = tvDevices.TopNode.Nodes[0].FirstNode;
                    labChlDevText.Text = tvDevices.TopNode.Nodes[0].FirstNode.Text;
                    tvDevices_AfterSelect(null, new TreeViewEventArgs(tvDevices.TopNode.FirstNode.FirstNode));
                }
                return true;
            }
        }
        private bool RefreshDevTree(ref TreeNode node, Channel Chl)
        {
            InnerModbusChannel tempChl = null;
            if (Chl is InnerModbusChannel)
            {
                tempChl = Chl as InnerModbusChannel;
            }

            if (tempChl != null)
            {
                for (int j = 0; j < tempChl.m_DeviceList.Count; j++)
                {
                    node.Nodes.Add(tempChl.m_DeviceList[j].DeviceId.ToString(), tempChl.m_DeviceList[j].Name);
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 刷新数值
        /// </summary>
        /// <param name="iChl"></param>
        /// <param name="iDev"></param>
        /// <returns></returns>
        private bool RefreshValue(int iChl, int iDev)
        {
            if (iChl > AppMain.ChlList.Count || iChl < 0)
            {
                picChlSta.BackgroundImage = Resources.StopSta;
                picDevSta.BackgroundImage = Resources.StopSta;
                return false;
            }
            AppMain.ChlList[iChl].PollingTime = (int)numPollingTime.Value; 
            return ShowChannelValue(AppMain.ChlList[iChl], iDev);
        }
        /// <summary>
        /// 刷新数值
        /// </summary>
        /// <param name="Chl"></param>
        /// <param name="iDev"></param>
        /// <returns></returns>
        private bool ShowChannelValue(Channel Chl,int iDev)
        {
            if (m_iChlId >= 0  && m_iChlId < AppMain.ChlList.Count && AppMain.ChlList[m_iChlId].GetChannelState()) // 通道状态
            {
                btnChlRWCtrl.Text = Resources.ChannelTurnOff;
                picChlSta.BackgroundImage = Resources.StartSta;
                cbbCOM.Enabled = false;
            }
            else
            {
                btnChlRWCtrl.Text = Resources.ChannelTurnOn;
                picChlSta.BackgroundImage = Resources.StopSta;
                cbbCOM.Enabled = true;
            }
            int Cnt = AppMain.ChlList[m_iChlId].GetDevicesCnt();
            if (iDev < 0 || iDev >= Cnt)
            {
                picDevSta.BackgroundImage = Resources.StopSta;
                return false;
            }
            BaseDevice baseDev = AppMain.ChlList[m_iChlId].GetDevByIndex(iDev);
            if (baseDev.isWorking&&baseDev.isConnected) // 装置状态
            {
                picDevSta.BackgroundImage = Resources.StartSta;
            }
            else
            {
                picDevSta.BackgroundImage = Resources.StopSta;
            }

            for (int i = 0; i < baseDev.GetDataItemCnt(); i++)
            {
                if ( i>= dgvShowValue.RowCount)
                {
                    break;
                }

                dgvShowValue[2, i].Value = baseDev.GetDataItem(i).dCurValue.ToString(baseDev.GetDataItem(i).strFormat);
                dgvShowValue[3, i].Value = baseDev.GetDataItem(i).dAverage.ToString(baseDev.GetDataItem(i).strFormat);
                if (baseDev.GetDataItem(i).dMinValue == null)
                {
                    dgvShowValue[4, i].Value ="-";
                }
                else
                {
                    dgvShowValue[4, i].Value = ((double)baseDev.GetDataItem(i).dMinValue).ToString(baseDev.GetDataItem(i).strFormat);
                }
                if (baseDev.GetDataItem(i).dMaxValue == null)
                {
                    dgvShowValue[5, i].Value = "-";
                }
                else
                {
                    dgvShowValue[5, i].Value = ((double)baseDev.GetDataItem(i).dMaxValue).ToString(baseDev.GetDataItem(i).strFormat);
                }
                
                

                if (dgvShowValue.Columns[10].Visible)
                {
                    if (!string.IsNullOrEmpty(baseDev.Expression))  // 设备层脚本
                    {
                        baseDev.ExecuteScript();
                    }
                    dgvShowValue[10, i].Value = baseDev.GetDataItem(i).CustomDisplay; // 自定义显示
                }
            }
            txtReFlashTime.Text = baseDev.m_FreshTime.ToString("yyyy-MM-dd HH:mm:ss");
            return true;
        }


        private void tvDevices_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (tvDevices.SelectedNode.Name == _strRootName || tvDevices.SelectedNode == null) // 固定名称
                {
                    m_iChlId = -1;
                    m_iDevId = -1;
                }
                else
                {
                    m_iDevId = GetDevIdFromSelNode(tvDevices.SelectedNode);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
            if (m_iDevId != -1 && m_iChlId !=-1)
            {
                numPollingTime.Value = AppMain.ChlList[m_iChlId].PollingTime; 
                BaseDevice baseDev = AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId);
                InnerModbusChannel channel = null;
                if (baseDev == null)
                {
                    return;
                }
                numAddr.Value = baseDev.bAddr;
                labChlDevText.Text = AppMain.ChlList[m_iChlId].baseChlPara.ChannelName +"-"+ baseDev.Name;
                channel = AppMain.ChlList[m_iChlId] as InnerModbusChannel;
                if (channel != null)
                {
                    cbbCOM.Text = channel.ComChlPara.ComPort.PortName; 
                }
                if (baseDev.isWorking)
                {
                    ckbIsWorking.CheckState = CheckState.Checked;
                }
                else
                {
                    ckbIsWorking.CheckState = CheckState.Unchecked;
                }
                int rowCnt = dgvShowValue.Rows.Count, DataCnt = baseDev.GetDataItemCnt();
                if (rowCnt < DataCnt)
                {
                    dgvShowValue.Rows.Add(DataCnt - rowCnt);
                }
                else
                {
                    for (int i = rowCnt; i > DataCnt; i--)
                    {
                        dgvShowValue.Rows.RemoveAt(i - 1);
                    }
                }
                
                for (int i = 0; i < DataCnt; i++)
                {

                    if (baseDev.GetDataItem(i).IsSave)
                    {
                        dgvShowValue[2, i].Style.BackColor = Color.Azure;
                    }
                    else
                    {
                        dgvShowValue[2, i].Style.BackColor = Color.LightYellow;
                    }
                    dgvShowValue[0, i].Value = i;
                    dgvShowValue[1, i].Value = baseDev.GetDataItem(i).Name;
                    dgvShowValue[2, i].Value = baseDev.GetDataItem(i).dCurValue.ToString(baseDev.GetDataItem(i).strFormat);
                    dgvShowValue[3, i].Value = baseDev.GetDataItem(i).dAverage.ToString(baseDev.GetDataItem(i).strFormat);
                    if (baseDev.GetDataItem(i).dMinValue == null)
                    {
                        dgvShowValue[4, i].Value = "-";
                    }
                    else
                    {
                        dgvShowValue[4, i].Value = ((double)baseDev.GetDataItem(i).dMinValue).ToString(baseDev.GetDataItem(i).strFormat);
                    }
                    if (baseDev.GetDataItem(i).dMaxValue == null)
                    {
                        dgvShowValue[5, i].Value = "-";
                    }
                    else
                    {
                        dgvShowValue[5, i].Value = ((double)baseDev.GetDataItem(i).dMaxValue).ToString(baseDev.GetDataItem(i).strFormat);
                    }
                    //dgvShowValue[4, i].Value = ((double)baseDev.GetDataItem(i).dMinValue).ToString(baseDev.GetDataItem(i).strFormat);
                    //dgvShowValue[5, i].Value = ((double)baseDev.GetDataItem(i).dMaxValue).ToString(baseDev.GetDataItem(i).strFormat);
                    dgvShowValue[6, i].Value = baseDev.GetDataItem(i).dmult;
                    dgvShowValue[7, i].Value = baseDev.GetDataItem(i).isLock;
                    dgvShowValue[8, i].Value = baseDev.GetDataItem(i).isLock;
                    dgvShowValue[9, i].Value = "";
                    dgvShowValue[10, i].Value = baseDev.GetDataItem(i).CustomDisplay; // 自定义显示
                }        
            }
            else
            {
                labChlDevText.Text = "";
                dgvShowValue.Rows.Clear();
            }
        }
        /// <summary>
        /// 从节点获取设备号  选中节点不是设备则是-1
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private int GetDevIdFromSelNode(TreeNode node)
        {
            InnerModbusChannel tempChl = null;
            for (int i = 0; i < AppMain.ChlList.Count; i++)  // 寻找通道
            {
                if (tvDevices.SelectedNode.Parent.Name == AppMain.ChlList[i].baseChlPara.ChannelId.ToString())
                {
                    if (AppMain.ChlList[i] is InnerModbusChannel)
                    {
                        tempChl = AppMain.ChlList[i] as InnerModbusChannel;
                    }
                    if (tempChl == null)
                    {
                        return -1;
                    }
                    m_iChlId = i;
                    break;
                }
                if (tvDevices.SelectedNode.Parent.Name == _strRootName && 
                    tvDevices.SelectedNode.Name == AppMain.ChlList[i].baseChlPara.ChannelId.ToString())
                {
                    m_iChlId = i;
                    return -1;
                }
            }

            if (tempChl == null)
            {
                return -1;
            }
            for (int j = 0; j < tempChl.m_DeviceList.Count; j++)  // 寻找对应设备
            {
                if (tvDevices.SelectedNode.Name == tempChl.m_DeviceList[j].DeviceId.ToString())
                {
                    return tempChl.m_DeviceList[j].DeviceId;
                }
            }
            return -1;
        }

        private void ShowDevValue_Activated(object sender, EventArgs e)
        {
            //RefreshChlTree();
            timer1.Enabled = true;
        }

        private void ShowDevValue_Deactivate(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

        private void btnChlRWCtrl_Click(object sender, EventArgs e)
        {
            ///if (!AppMain.isRegisted)
            //{
            //    MessageBox.Show(Resources.MsgPleaseRegistApp, Resources.msgTitleTip, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            //    return;
            //}
          
            if (m_iChlId == -1)
            {
                return;
            }
            if (btnChlRWCtrl.Text == Resources.ChannelTurnOn)
            {
                AppMain.ChlList[m_iChlId].StartPolling();
            }
            else
            {
                AppMain.ChlList[m_iChlId].StopPolling();
            }
        }

        private void btnSendModify_Click(object sender, EventArgs e)
        {
            if (m_iChlId < 0 || m_iDevId < 0 || dgvShowValue.RowCount == 0)
            {
                MessageBox.Show(Resources.MsgSelDevAndAddValueTips);
            }
            if (!AppMain.ChlList[m_iChlId].GetChannelState() || AppMain.ChlList[m_iChlId].GetInsertFrameCnt() > 50)
            {
                return;
            }
            List<DevDataItem> DataItem = new List<DevDataItem>();
            DevDataItem temp = null, RefDataItem = null;
            for (int i = 0; i < dgvShowValue.RowCount; i++)
            {
                temp = new DevDataItem();
                if (AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).GetDataItem(i).isLock && dgvShowValue[9, i].Value != null)
                {
                    RefDataItem = AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).GetDataItem(i);
                    RefDataItem.ItemId = i;
                    temp.CopyFrom(RefDataItem);
                    if (double.TryParse(dgvShowValue[9, i].Value.ToString(), out temp.dWriteValue))
                    {
                        temp.bFunCode = 0x10;
                        DataItem.Add(temp);
                        DataItem.Add(RefDataItem);
                    }
                }
            }
            if (DataItem.Count > 0)
            {
                AppMain.ChlList[m_iChlId].InsertFrame(m_iDevId, DataItem);
            }
           
        }

        /// <summary>
        /// Modbus 协议自定义对时 固定对时地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoSetTime_Click(object sender, EventArgs e)
        {
            if (m_iChlId < 0 || m_iDevId < 0)
            {
                MessageBox.Show(Resources.MsgSelDeviceTips);
            }
            if (AppMain.ChlList[m_iChlId].GetInsertFrameCnt() > 10)
            {
                return ;
            }
            ModbusInfo modInfo;
            DateTime dt = DateTime.Now;
            int[] TimeValue = { dt.Second, dt.Minute, dt.Hour, dt.Day, dt.Month, dt.Year - 2000 };
            for (int i = 0; i < 6; i++)
            {
                modInfo = new ModbusInfo();
                modInfo.DevAddr = AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).bAddr;
                modInfo.FunCode = 0x10;
                modInfo.RegAddr = (ushort)(0x0085-i);
                modInfo.RegNum = 1;
                modInfo.WriteData = BitConverter.GetBytes((ushort)TimeValue[i]);
                Array.Reverse(modInfo.WriteData, 0, 2);
                AppMain.ChlList[m_iChlId].InsertFrame(modInfo);
            }
        }

        private void ckbIsWorking_CheckStateChanged(object sender, EventArgs e)
        {
            if (m_iChlId < 0 || m_iDevId < 0)
            {
                MessageBox.Show(Resources.MsgSelDeviceTips);
            }
            if (ckbIsWorking.CheckState == CheckState.Checked)
            {
                AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).isWorking = true;
            }
            else
            {
                //AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).isConnected = false;
                AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).isWorking = false;
            }
        }

        /// <summary>
        /// 单元格数值改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvShowValue_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvShowValue_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 8|| e.RowIndex<0 || m_iChlId < 0 || m_iDevId < 0)
            {
                return;
            }
            if (dgvShowValue[8, e.RowIndex].Value != null)
            {
                AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).GetDataItem(e.RowIndex).isLock = !AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId).GetDataItem(e.RowIndex).isLock;
            }
        }


        private void dgvShowValue_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex != 2 || m_iChlId < 0 || m_iDevId < 0 || e.RowIndex < 0)
            {
                return;
            }
            BaseDevice baseDev = AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId);
            if (e.RowIndex >= baseDev.GetDataItemCnt())//!baseDev.isWorking || !baseDev.isConnected || 
            {
                //MessageBox.Show("当前设备通信已中断!\n无法显示实时曲线！", Properties.Resources.msgTitleTip);
                return;
            }
            ShowChart chart = new ShowChart(baseDev,m_iChlId, m_iDevId, e.RowIndex);
            chart.ShowDialog();
        }
        /// <summary>
        /// 右键列标题时弹出菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvShowValue_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    dgvShowValue.ContextMenuStrip = null;
                }
                else
                {
                    dgvShowValue.ContextMenuStrip = ctmsDispearCol;
                }
            }
        }
        private void tsmiAverage_Click(object sender, EventArgs e)
        {
            if (tsmiAverage.CheckState == CheckState.Checked)
            {
                dgvShowValue.Columns[3].Visible = true;
            }
            else
            {
                dgvShowValue.Columns[3].Visible = false;
            }
            ModifyNode(0);
        }

        private void tsmiMinValue_Click(object sender, EventArgs e)
        {
            if (tsmiMinValue.CheckState == CheckState.Checked)
            {
                dgvShowValue.Columns[4].Visible = true;
            }
            else
            {
                dgvShowValue.Columns[4].Visible = false;
            }
            ModifyNode(1);
        }

        private void tsmiMaxValue_Click(object sender, EventArgs e)
        {
            if (tsmiMaxValue.CheckState == CheckState.Checked)
            {
                dgvShowValue.Columns[5].Visible = true;
            }
            else
            {
                dgvShowValue.Columns[5].Visible = false;
            }
            ModifyNode(2);
        }

        private void tsmiRatio_Click(object sender, EventArgs e)
        {
            if (tsmiRatio.CheckState == CheckState.Checked)
            {
                dgvShowValue.Columns[6].Visible = true;
            }
            else
            {
                dgvShowValue.Columns[6].Visible = false;
            }
            ModifyNode(3);
        }

        private void tsmiIsModify_Click(object sender, EventArgs e)
        {
            if (tsmiIsModify.CheckState == CheckState.Checked)
            {
                dgvShowValue.Columns[8].Visible = true;
            }
            else
            {
                dgvShowValue.Columns[8].Visible = false;
            }
            ModifyNode(4);
        }

        private void tsmiModifyValue_Click(object sender, EventArgs e)
        {
            if (tsmiModifyValue.CheckState == CheckState.Checked)
            {
                dgvShowValue.Columns[9].Visible = true;
            }
            else
            {
                dgvShowValue.Columns[9].Visible = false;
            }
            ModifyNode(5);
        }

        private void tsmiScriptResult_Click(object sender, EventArgs e)
        {
            if (tsmiScriptResult.CheckState == CheckState.Checked)
            {
                dgvShowValue.Columns[10].Visible = true;
            }
            else
            {
                dgvShowValue.Columns[10].Visible = false;
            }
            ModifyNode(6);
        }

        private void cbbCOM_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_iDevId != -1 && m_iChlId != -1)
            {
                InnerModbusChannel channel = null;
                channel = AppMain.ChlList[m_iChlId] as InnerModbusChannel;
                if (channel != null)
                {
                    channel.ComChlPara.ComPort.PortName = cbbCOM.Text;
                }
            }
        }

        private void dgvShowValue_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (m_iDevId == -1 || m_iChlId == -1)
            {
                return;
            }
            if (e.ColumnIndex == 8)
            {
                BaseDevice dev = AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId);
                if (dev.GetDataItemCnt() <= 0)
                {
                    return;
                }
                bool bValue = dev.GetDataItem(0).isLock;
                for (int i = 0; i < dev.GetDataItemCnt(); i++)
                {
                    dev.GetDataItem(i).isLock = !bValue;
                    if (i < dgvShowValue.RowCount)
                    {
                        dgvShowValue.Rows[i].Cells[e.ColumnIndex].Value = !bValue;
                    }
                }
            }
        }

        private void btnSavePara_Click(object sender, EventArgs e)
        {
            if (m_iChlId == -1)
            {
                return;
            }
            if (AppMain.UpdateChlParaToDB(AppMain.ChlList[m_iChlId]))
           {
               MessageBox.Show(Resources.MsgSaveSucceed);
           } 
           else
           {
               MessageBox.Show(Resources.MsgSaveFailed);
           }
        }

        private void btnSaveDevConfig_Click(object sender, EventArgs e)
        {
            if (m_iDevId == -1 || m_iChlId == -1)
            {
                return;
            }
            using (OleDbConnection con = new OleDbConnection(dbOper.M_str_sqlcon))
            {
                InnerModbusChannel channel = null;
                channel = AppMain.ChlList[m_iChlId] as InnerModbusChannel;
                BaseDevice dev = AppMain.ChlList[m_iChlId].GetDevByIndex(m_iDevId);
                if (channel != null && dev!=null)
                {
                    dev.bAddr = (byte)numAddr.Value;
                    if (AppMain.UpdateDevParaToDB(channel.baseChlPara.ChannelId,dev, con))
                    {
                        MessageBox.Show(Resources.MsgSaveSucceed);
                    }
                    else
                    {
                        MessageBox.Show(Resources.MsgSaveFailed);
                    }
                }
            }
          
        }

        private void ShowDevValue_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (e.CloseReason == CloseReason.UserClosing)
            //{
            //    e.Cancel = true;
            //} 
        }


        //private void dgvShowValue_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        //{
        //    if (e.RowIndex % 2 == 0)
        //    {
        //        dgvShowValue.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(155, 227, 207);
        //    } 
        //}

    }
}
